import "package:flutter/material.dart";
import 'package:flutter_pink_app/route/delegate.dart';
import 'package:flutter_pink_app/route/page.dart';
import '../serialized/recommend.dart';
import "video_card.dart";
import '../util.dart';

// 二维滚动瀑布流组合
class Feed2DList extends StatelessWidget {
  Feed2DList(this._videolist,
      {this.padding = const EdgeInsets.symmetric(horizontal: 6),
      this.refreshDistance = 200,
      this.refreshCallback})
      : _scrollController = ScrollController() {
    // 如果存在刷新函数，在构造函数中为控制器添加防抖监听
    if (refreshCallback != null) {
      // 包装底部刷新函数
      final _listener = () {
        final position = _scrollController.hasClients
            ? _scrollController.position
            : null; // 安全检测
        if (position != null &&
            position.maxScrollExtent - position.pixels < refreshDistance) {
          print("调用了feed流刷新函数");
          refreshCallback();
        }
      };
      _scrollController.addListener(
          debounce(Duration(milliseconds: 100), _listener)); // 100ms防抖
    }
  }

  final List<VideoInfo> _videolist; // 影片信息列表
  final EdgeInsetsGeometry padding; // 内边距
  final ScrollController _scrollController; // 滚动控制器
  final VoidCb refreshCallback; // 刷新时调用的函数
  final double refreshDistance; // 刷新调用函数触发的距离

  // 创建网格算法代理
  SliverGridDelegateWithFixedCrossAxisCount _createGridDelegate() {
    return SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: 2, // 横轴数量2
      crossAxisSpacing: 6, // 横轴间距为10
    );
  }

  // 处理影片页面跳转函数
  void _jumpToVideoPage(BuildContext ctx, VideoInfo info) {
    final delegate = BiliRouterDelegate.of(ctx); // 取得路由代理
    delegate.push(BiliPageStatus('/video', videoInfo: info));
  }

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
      controller: _scrollController,
      padding: padding,
      physics: BouncingScrollPhysics(),
      gridDelegate: _createGridDelegate(),
      itemCount: _videolist.length, // 影片列表数量
      itemBuilder: (_, int index) {
        return LayoutBuilder(
          builder: (_, BoxConstraints constraints) {
            return VideoCard(_videolist[index], constraints.maxHeight,
                onTap: _jumpToVideoPage);
          },
        );
      },
    );
  }
}
